//
//  NZKAlertView.m
//  ProjectBoss
//
//  Created by 聂志康 on 2018/8/22.
//  Copyright © 2018 weipainetwork. All rights reserved.
//

#import "NZKAlertView.h"

#define AlertViewWidth ([UIScreen mainScreen].bounds.size.width-50*2)

@interface NZKAlertView ()
@property (nonatomic, strong) UIView *backGroundAlphaView;
@end

@implementation NZKAlertView

- (instancetype)initWithTitle:(nullable NSString *)title message:(nullable NSString *)message delegate:(nullable id <NZKAlertViewDelegate>)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitle:(nullable NSString *)otherButtonTitle {
    CGFloat alertViewHeight = 34;
    if (title) {
        CGRect TitleRect = [title boundingRectWithSize:CGSizeMake(AlertViewWidth, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10]} context:nil];
        alertViewHeight += TitleRect.size.height+10*2;
    }
    if (message) {
        CGRect MessageRect = [message boundingRectWithSize:CGSizeMake(AlertViewWidth, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10]} context:nil];
        alertViewHeight += MessageRect.size.height+26*2;
    }
    self = [super initWithFrame:CGRectMake(0, 0, AlertViewWidth, alertViewHeight)];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:(238 / 255.0) green:(238 / 255.0) blue:(238 / 255.0) alpha:1.0];
        self.alpha = 0.0;
        self.layer.cornerRadius = 8;
        self.layer.masksToBounds = true;
        self.delegate = delegate;
        CGRect TitleRect = [title boundingRectWithSize:CGSizeMake(AlertViewWidth, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10]} context:nil];
        CGRect MessageRect = [message boundingRectWithSize:CGSizeMake(AlertViewWidth, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10]} context:nil];
        if (title) {
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, AlertViewWidth, TitleRect.size.height+10*2-0.5) andText:title andTextColor:[UIColor colorWithRed:(51 / 255.0) green:(51 / 255.0) blue:(51 / 255.0) alpha:1.0] andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:10] andTextAlignment:NSTextAlignmentCenter];
            titleLabel.backgroundColor = UIColor.whiteColor;
            [self addSubview:titleLabel];
        }
        if (message) {
            CGRect messageLabelRect;
            if (title) {
                messageLabelRect = CGRectMake(0, TitleRect.size.height+10*2, AlertViewWidth, MessageRect.size.height+26*2-0.5);
            } else {
                messageLabelRect = CGRectMake(0, 0, AlertViewWidth, MessageRect.size.height+26*2-0.5);
            }
            UILabel *messageLabel = [[UILabel alloc] initWithFrame:messageLabelRect andText:message andTextColor:[UIColor colorWithRed:(51 / 255.0) green:(51 / 255.0) blue:(51 / 255.0) alpha:1.0] andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:12] andTextAlignment:NSTextAlignmentCenter];
            messageLabel.backgroundColor = UIColor.whiteColor;
            [self addSubview:messageLabel];
        }
        if (otherButtonTitle) {
            UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, alertViewHeight-34, AlertViewWidth/2-0.5, 34)];
            UIButton *otherButton = [[UIButton alloc] initWithFrame:CGRectMake(AlertViewWidth/2, alertViewHeight-34, AlertViewWidth/2, 34)];
            cancelButton.backgroundColor = UIColor.whiteColor;
            [cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [cancelButton setTitleColor:[UIColor colorWithRed:(51 / 255.0) green:(51 / 255.0) blue:(51 / 255.0) alpha:1.0] forState:UIControlStateNormal];
            cancelButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
            [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:cancelButton];
            otherButton.backgroundColor = UIColor.whiteColor;
            [otherButton setTitle:otherButtonTitle forState:UIControlStateNormal];
            [otherButton setTitleColor:[UIColor colorWithRed:(248 / 255.0) green:(142 / 255.0) blue:(32 / 255.0) alpha:1.0] forState:UIControlStateNormal];
            otherButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
            [otherButton addTarget:self action:@selector(otherButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:otherButton];
        } else {
            UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, alertViewHeight-34, AlertViewWidth, 34)];
            cancelButton.backgroundColor = UIColor.whiteColor;
            [cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [cancelButton setTitleColor:[UIColor colorWithRed:(51 / 255.0) green:(51 / 255.0) blue:(51 / 255.0) alpha:1.0] forState:UIControlStateNormal];
            cancelButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
            [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:cancelButton];
        }
        self.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
    }
    return self;
}

- (instancetype)initWithCustomView:(nullable UIView *)customView title:(nullable NSString *)title delegate:(nullable id<NZKAlertViewDelegate>)delegate cancelButtonTitle:(nullable NSString *)cancelButtonTitle otherButtonTitle:(nullable NSString *)otherButtonTitle {
    CGFloat alertViewHeight = 34;
    if (title) {
        CGRect TitleRect = [title boundingRectWithSize:CGSizeMake(AlertViewWidth, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10]} context:nil];
        alertViewHeight += TitleRect.size.height+10*2;
    }
    if (customView) {
        CGRect customFrame = customView.frame;
        alertViewHeight += customFrame.size.height+20*2;
    }
    self = [super initWithFrame:CGRectMake(0, 0, AlertViewWidth, alertViewHeight)];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:(238 / 255.0) green:(238 / 255.0) blue:(238 / 255.0) alpha:1.0];
        self.alpha = 0.0;
        self.layer.cornerRadius = 8;
        self.layer.masksToBounds = true;
        self.delegate = delegate;
        CGRect TitleRect = [title boundingRectWithSize:CGSizeMake(AlertViewWidth, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10]} context:nil];
        if (title) {
            UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, AlertViewWidth, TitleRect.size.height+10*2-0.5) andText:title andTextColor:[UIColor colorWithRed:(51 / 255.0) green:(51 / 255.0) blue:(51 / 255.0) alpha:1.0] andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:10] andTextAlignment:NSTextAlignmentCenter];
            titleLabel.backgroundColor = UIColor.whiteColor;
            [self addSubview:titleLabel];
        }
        if (customView) {
            CGRect customFrame = customView.frame;
            if (title) {
                customFrame = CGRectMake((AlertViewWidth-customFrame.size.width)/2, TitleRect.size.height+10*2+20, customFrame.size.width, customFrame.size.height);
            } else {
                customFrame = CGRectMake(0, 20, customFrame.size.width, customFrame.size.height);
            }
            customView.frame = customFrame;
            [self addSubview:customView];
        }
        if (otherButtonTitle) {
            UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, alertViewHeight-34, AlertViewWidth/2-0.5, 34)];
            UIButton *otherButton = [[UIButton alloc] initWithFrame:CGRectMake(AlertViewWidth/2, alertViewHeight-34, AlertViewWidth/2, 34)];
            cancelButton.backgroundColor = UIColor.whiteColor;
            [cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [cancelButton setTitleColor:[UIColor colorWithRed:(51 / 255.0) green:(51 / 255.0) blue:(51 / 255.0) alpha:1.0] forState:UIControlStateNormal];
            cancelButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
            [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:cancelButton];
            otherButton.backgroundColor = UIColor.whiteColor;
            [otherButton setTitle:otherButtonTitle forState:UIControlStateNormal];
            [otherButton setTitleColor:[UIColor colorWithRed:(248 / 255.0) green:(142 / 255.0) blue:(32 / 255.0) alpha:1.0] forState:UIControlStateNormal];
            otherButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
            [otherButton addTarget:self action:@selector(otherButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:otherButton];
        } else {
            UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(0, alertViewHeight-34, AlertViewWidth, 34)];
            cancelButton.backgroundColor = UIColor.whiteColor;
            [cancelButton setTitle:cancelButtonTitle forState:UIControlStateNormal];
            [cancelButton setTitleColor:[UIColor colorWithRed:(51 / 255.0) green:(51 / 255.0) blue:(51 / 255.0) alpha:1.0] forState:UIControlStateNormal];
            cancelButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
            [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:cancelButton];
        }
        self.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
        
        #pragma mark - 键盘事件
        //监听当键盘将要出现时
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification
                                                   object:nil];
        
        //监听当键将要退出时
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }
    return self;
}

- (instancetype)initWithImageView:(UIImageView *)imageView title:(nullable NSString *)title delegate:(nullable id<NZKAlertViewDelegate>)delegate buttonTitle:(nullable NSString *)buttonTitle {
    CGRect TitleRect = [title boundingRectWithSize:CGSizeMake(AlertViewWidth-100, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:18]} context:nil];
    CGFloat titleLabelWidthPlusHundred = 100.0f;
    if (TitleRect.size.width+100 < 220) {
        titleLabelWidthPlusHundred = 220.0f;
    } else if (TitleRect.size.width+100 > AlertViewWidth) {
        titleLabelWidthPlusHundred = AlertViewWidth;
    } else {
        titleLabelWidthPlusHundred = TitleRect.size.width+100;
    }
    CGRect newTitleRect = [title boundingRectWithSize:CGSizeMake(titleLabelWidthPlusHundred-100, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:18]} context:nil];
    CGFloat alertViewHeight = 40+40+40;
    if (imageView) {
        alertViewHeight += (imageView.bounds.size.height+20);
    }
    if (title) {
        alertViewHeight += newTitleRect.size.height+20;
    }
    self = [super initWithFrame:CGRectMake(0, 0, titleLabelWidthPlusHundred, alertViewHeight)];
    if (self) {
        self.backgroundColor = UIColor.whiteColor;
        self.alpha = 0.0;
        self.layer.cornerRadius = 8;
        self.layer.masksToBounds = true;
        self.delegate = delegate;
        if (imageView) {
            CGRect formerImageViewFrame = imageView.frame;
            imageView.frame = CGRectMake((titleLabelWidthPlusHundred-formerImageViewFrame.size.width)/2, 40, formerImageViewFrame.size.width, formerImageViewFrame.size.height);
            [self addSubview:imageView];
        }
        if (title) {
            UILabel *titleLabel;
            if (imageView) {
                titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 40+imageView.bounds.size.height+20, titleLabelWidthPlusHundred-100, newTitleRect.size.height) andText:title andTextColor:NAV_COLOR andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:18] andTextAlignment:NSTextAlignmentCenter];
            } else {
                titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 40, titleLabelWidthPlusHundred-100, newTitleRect.size.height+10*2-0.5) andText:title andTextColor:NAV_COLOR andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:18] andTextAlignment:NSTextAlignmentCenter];
            }
            titleLabel.backgroundColor = UIColor.clearColor;
            titleLabel.numberOfLines = 0;
            [self addSubview:titleLabel];
        }
        
        UIButton *cancelButton = [[UIButton alloc] initWithFrame:CGRectMake((titleLabelWidthPlusHundred-150)/2, alertViewHeight-40-40, 150, 40)];
        cancelButton.backgroundColor = hexColor(eeeeee);
        cancelButton.layer.cornerRadius = 8;
        cancelButton.layer.masksToBounds = true;
        cancelButton.layer.borderColor = COLOR(153, 153, 153, 1).CGColor;
        cancelButton.layer.borderWidth = 1.0f;
        [cancelButton setTitle:buttonTitle forState:UIControlStateNormal];
        [cancelButton setTitleColor:hexColor(333333) forState:UIControlStateNormal];
        cancelButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:17];
        [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cancelButton];
            
        self.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
    }
    return self;
}

- (void)cancelButtonClick {
    if ([self.delegate respondsToSelector:@selector(didClickCancelButtonOnNZKAlertView:)]) {
        [self.delegate didClickCancelButtonOnNZKAlertView:self];
    }
    [self done];
}

- (void)otherButtonClick {
    if ([self.delegate respondsToSelector:@selector(didClickOtherButtonOnNZKAlertView:)]) {
        [self.delegate didClickOtherButtonOnNZKAlertView:self];
    }
    [self done];
}

- (void)show {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.backGroundAlphaView];
    [window addSubview:self];
    __weak __typeof(&*self)weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.backGroundAlphaView.alpha = 0.5;
        weakSelf.alpha = 1.0;
    }];
}
//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification
{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    if (([UIScreen mainScreen].bounds.size.height-self.frame.size.height)/2 < height+8) {
        [UIView animateWithDuration:0.25 animations:^{
            self.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height-(height+8+self.frame.size.height/2));
        }];
    }
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification
{
    [UIView animateWithDuration:0.25 animations:^{
        self.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2, [UIScreen mainScreen].bounds.size.height/2);
    }];
}

- (void)done {
    [self endEditing:true];
    __weak __typeof(&*self)weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.backGroundAlphaView.alpha = 0.0;
        weakSelf.alpha = 0.0;
    } completion:^(BOOL finished) {
        [weakSelf.backGroundAlphaView removeFromSuperview];
        [weakSelf removeFromSuperview];
    }];
}

- (UIView *)backGroundAlphaView {
    if (!_backGroundAlphaView) {
        _backGroundAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        _backGroundAlphaView.backgroundColor = UIColor.blackColor;
        _backGroundAlphaView.alpha = 0.0;
    }
    return _backGroundAlphaView;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
